// services/SmsService.js
const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const { models } = require('../models');
const logger = require('../utils/logger');

class SmsService {
  /**
   * 发送短信验证码
   * @param {Object} options 短信发送参数
   * @param {string} options.phone 手机号码
   * @param {string} options.type 短信类型
   * @param {string} options.ip 发送IP
   * @returns {Promise<Object>} 发送结果
   */
  static async sendVerificationCode(options) {
    const { phone, type, ip } = options;
    
    // 生成6位随机验证码
    const verificationCode = Math.floor(100000 + Math.random() * 900000).toString();
    
    try {
      // 初始化阿里云短信客户端
      const config = new OpenApi.Config({
        accessKeyId: process.env.ALI_SMS_ACCESS_KEY_ID,
        accessKeySecret: process.env.ALI_SMS_ACCESS_KEY_SECRET
      });
      
      const client = new Dysmsapi20170525.Client(config);
      
      // 构建短信请求
      const sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
        phoneNumbers: phone,
        signName: process.env.ALI_SMS_SIGN_NAME,
        templateCode: process.env.ALI_SMS_TEMPLATE_CODE,
        templateParam: JSON.stringify({ code: verificationCode })
      });
      
      // 发送短信
      const result = await client.sendSms(sendSmsRequest);
      
      // 记录短信日志
      const smsLog = await models.SmsLog.create({
        phone,
        sms_type: type,
        verification_code: verificationCode,
        ali_response: JSON.stringify(result),
        send_status: result.body.code === 'OK' ? 'SUCCESS' : 'FAILED',
        send_ip: ip,
        error_message: result.body.code !== 'OK' ? result.body.message : null
      });
      
      // 记录日志
      logger.info(`短信发送记录: ${smsLog.log_id}`);
      
      return {
        success: result.body.code === 'OK',
        verificationCode,
        logId: smsLog.log_id
      };
      
    } catch (error) {
      // 记录错误日志
      logger.error('短信发送失败', { error, phone, type });
      
      // 记录失败的短信日志
      await models.SmsLog.create({
        phone,
        sms_type: type,
        send_status: 'FAILED',
        send_ip: ip,
        error_message: error.message
      });
      
      throw error;
    }
  }
  
  /**
   * 验证短信验证码
   * @param {Object} options 验证参数
   * @param {string} options.phone 手机号码
   * @param {string} options.code 验证码
   * @param {string} options.type 短信类型
   * @returns {Promise<boolean>} 是否验证成功
   */
  static async verifyCode(options) {
    const { phone, code, type } = options;
    
    // 查找最近的未过期且未使用的验证码
    const smsLog = await models.SmsLog.findOne({
      where: {
        phone,
        sms_type: type,
        verification_code: code,
        send_status: 'SUCCESS',
        is_used: false,
        expire_at: {
          [models.Sequelize.Op.gt]: new Date()
        }
      },
      order: [['created_at', 'DESC']]
    });
    
    // 如果找到有效的验证码，标记为已使用
    if (smsLog) {
      await smsLog.update({ is_used: true });
      return true;
    }
    
    return false;
  }
}

module.exports = SmsService;